package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.TimeUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constant.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.constant.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 2025/07/16
     * 查询店铺列表
     */
    @Override
    public Result queryTypeList() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        //查询redis
        String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        //存在数据，直接返回
        if(StrUtil.isNotBlank(shopTypeJson)){
            List<ShopType> shopTypeList = objectMapper.readValue(shopTypeJson, new TypeReference<List<ShopType>>() {});
            return Result.ok(shopTypeList);
        }
        //不存在，则查询数据库，返回数据并把数据存入redis
        LambdaQueryWrapper<ShopType> shopTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shopTypeLambdaQueryWrapper.orderByAsc(ShopType::getSort);
        List<ShopType> shopTypeList = list(shopTypeLambdaQueryWrapper);
        String valueAsString = objectMapper.writeValueAsString(shopTypeList);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,valueAsString,CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        return Result.ok(shopTypeList);
    }
}
